import React from 'react'
import { useSelector } from 'react-redux'
import type { RootState } from'../store/store'
import { useLocation, Navigate } from 'react-router-dom'

const Permission: React.FC<{ children:React.ReactNode }> = ({ children }) => {
  const location = useLocation()

  const userInfo = useSelector((state: RootState) => state.user.userInfo)
  // 读取用户所有权限
  const permission = useSelector((state: RootState) => state.user.userInfo?.permission ?? [])
  // 根据当前访问地址判断是否有此权限
  const isPermission = permission.find(item => item.path === location.pathname)
  // 初始值为空  则阻断向下
  if(userInfo === null) return null
  // 有权限  返回 children  渲染页面
   if(isPermission) return children
  return <Navigate to="/403" />
}

export default Permission